package net.stancristian.restnews;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONException;

import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

public class ReaderActivity extends Activity {

	private ListView newsList;
	private NewsItemAdapter adapter;
	ScheduledExecutorService scheduler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reader);
		newsList = (ListView) findViewById(R.id.ListViewNews);

		// Set the Array Adapter
		ArrayList<NewsItemSmall> news = GetNewsList();
		adapter = new NewsItemAdapter(this, news);
		newsList.setAdapter(adapter);

		// On Click listener
		SetOnClickListener();

		// Start update service
		StartService();
	}

	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver,
				new IntentFilter(UpdatesService.NOTIFICATION));
	}

	private void StartService() {
		scheduler = Executors.newSingleThreadScheduledExecutor();
		scheduler.scheduleAtFixedRate(new Runnable() {

			public void run() {
				Intent intent = new Intent(getApplicationContext(),
						UpdatesService.class);
				startService(intent);
			}
		}, 15, 15, TimeUnit.SECONDS);

	}

	/*
	 * The Broadcast Receiver...............
	 */
	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			ArrayList<NewsItemSmall> news = GetNewsList();
			Iterator<NewsItemSmall> iter = news.iterator();

			adapter.clear();
			while (iter.hasNext()) {
				adapter.add(iter.next());
			}
			adapter.notifyDataSetChanged();
		}
	};

	/*
	 * Init the list
	 */
	private ArrayList<NewsItemSmall> GetNewsList() {
		String baseApiAddress = getString(R.string.api_base_address);
		String Url = baseApiAddress + "/News";
		ArrayList<NewsItemSmall> news = new ArrayList<NewsItemSmall>();

		HttpResponse response = RestNewsClient.getRequestWebService(Url);
		if (response != null
				&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			try {
				JSONArray array = RestNewsClient
						.GetJsonArrayFromResponse(response);

				for (int i = 0; i < array.length(); i++) {
					news.add(new NewsItemSmall(array.getJSONObject(i)));
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		return news;

	}

	private void SetOnClickListener() {
		newsList.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				NewsItemSmall newsItem = (NewsItemSmall) newsList
						.getItemAtPosition(position);
				Intent intent = new Intent(getBaseContext(),
						NewsItemActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt("news_item_id", newsItem.Id);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}

}
